#!/usr/bin/env bash

# 把容器镜像内容解压缩出来

full_img_ver=$1
target=$2

if [ -z "$target" ]; then
 echo "把容器镜像内容解压缩出来，参数：   完整的镜像名:版本号  目标文件夹  [层]"
 echo "实际参数: $full_img_ver,$target,$3"
 exit 1;
fi


SCRIPTDIR=$(cd $(dirname "${BASH_SOURCE[0]}") >/dev/null && pwd)
cd $SCRIPTDIR

rm -rf $target && mkdir -p  $target/docker-img   $target/docker-data

echo "打包镜像..."

docker save -o $target/docker-img.tar $full_img_ver

tar -xvf $target/docker-img.tar -C  $target/docker-img

filter=$3
if [ -n "$filter" ]; then
  filter="| grep ${filter}"
fi

echo "对镜像拆包..."
# $filter | sed '1d'
cat $target/docker-img/manifest.json | sed "s|\"|\n|g" | grep  layer.tar  | while read line; do
   tar -xvf $target/docker-img/$line  -C $target/docker-data
done

echo "解压镜像 $full_img_ver --> $target 完成"